package com.simple.datax.bo.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.simple.datax.bo.ITbResourcesBO;
import com.simple.datax.dao.ITbResourcesDAO;
import com.simple.datax.vo.TbResourcesVO;

@Service("tbResourcesBO")
@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
public class TbResourcesBOImpl implements ITbResourcesBO {	
	@SuppressWarnings({"rawtypes" })
    private Map<String,Map> tbResourceMap;
	
	@Autowired
    private ITbResourcesDAO tbResourcesDAO;
	
	@SuppressWarnings("rawtypes")
	@Override
	
	public Map<String,Map> getAllTbResourceMap(){
		if(tbResourceMap==null){
			buildMap();
		}
		return tbResourceMap;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void buildMap(){
		tbResourceMap = new HashMap<String,Map>();
		final List<TbResourcesVO> tbResourcesVOList = findAll();
        final Iterator<TbResourcesVO> iter =  tbResourcesVOList.iterator();
        while(iter.hasNext()){
            final TbResourcesVO tbResourcesVO = (TbResourcesVO)iter.next();
            HashMap<String, Map> pkMap = (HashMap<String, Map>) tbResourceMap.get(tbResourcesVO.getId().getPackageString());
            if(pkMap==null){
                pkMap = new HashMap<String,Map>();
                tbResourceMap.put(tbResourcesVO.getId().getPackageString(),pkMap);
            }
            Map<String,String> locMap = pkMap.get(tbResourcesVO.getId().getLocale());
            if(locMap==null){
                locMap = new HashMap<String,String>();
                pkMap.put(tbResourcesVO.getId().getLocale(),locMap);
            }
            
            locMap.put(tbResourcesVO.getId().getKey(), tbResourcesVO.getValue());
        }
	}


	@Override
	public List<TbResourcesVO> findAll() {
		return tbResourcesDAO.findAll();
	}

	@Override
	public List<TbResourcesVO> findByPackages(String[] packageAry) {
		return tbResourcesDAO.findByPackages(packageAry);
	}

	@Override
	public Map<String, String> findByPackagesLocale(String[] packageAry,
			String locale) {
		final Map<String, String> tbResourcesMap = new HashMap<String, String>();
        final List<TbResourcesVO> tbResourcesVOList = tbResourcesDAO.findByPackages(packageAry);

        final Iterator<TbResourcesVO> iter = tbResourcesVOList.iterator();
        while(iter.hasNext()){
            final TbResourcesVO tbResourcesVO = iter.next();
            if(tbResourcesVO.getId().getLocale().endsWith(locale)){
                tbResourcesMap.put(tbResourcesVO.getId().getKey(), tbResourcesVO.getValue());
            }
        }
        return tbResourcesMap;
	}

}
